//
//  ext.swift
//  XLProject
//
//  Created by xinglian on 2022/1/22.
//

import UIKit
import CommonCrypto
@objc public extension NSString
{
    
    
    func size(_ font : UIFont, _ width : CGFloat)->CGSize
    {
        let size = CGSize(width:width, height:CGFloat(MAXFLOAT))
        let rect = self.boundingRect(with: size, options: [.usesFontLeading,.usesLineFragmentOrigin,.truncatesLastVisibleLine], attributes: [NSAttributedString.Key.font:font], context: nil)
        return CGSize(width:ceil(rect.size.width), height:ceil(rect.size.height))
    }
    
    
    
    var md5: String
    {
        let str = self.cString(using: String.Encoding.utf8.rawValue)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8.rawValue))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        
        let hash = NSMutableString()
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        
        result.deallocate()
        return hash as String
    }
    
}

@objc public extension NSString{
    
    /// 十六进制色值，加透明度，转换成UIColor
    @objc func color(_ alpha : Float) -> UIColor{ return (self as String).color(alpha)}
    /// 十六进制色值转换成UIColor
    @objc func color() -> UIColor{return (self as String).color()}
    ///十六进制转换成十进制
    func toDemical()->Int{return (self as String).toDecimal()}
    ///十进制转换成十六进制
    func toHex()->NSString{return(self as String).toHex()}
    ///截取字符串
    func sub(_ start:Int, _ count:Int)->NSString{
        return(self as String).subString(start, count) as NSString
    }
    
    /// 字符串不足指定的位数时候，自动补全
    /// - Parameters:
    ///   - count: 指定显示的位数
    ///   - addString: 自动补全的字符串
    /// - Returns: 返回补全后的字符串，例如000001
    func fix(_ count:Int, _ addString:String)->NSString{
        return(self as String).fixString(count, addString) as NSString
    }
    
    func isMobie()->Bool{ return (self as String).isMobile()}
    func isNumber()->Bool{ return (self as String).isNumber()}
    func isChinese()->Bool{ return (self as String).isChinese()}
    func isNumberOrAlphabet()->Bool{ return (self as String).isNumberOrAlphabet()}
    func isNumOrChineseOrEnglish()->Bool{ return (self as String).isNumOrChineseOrEnglish()}
    func isInt()->Bool{ return (self as String).isInt()}
    func isFloat()->Bool{ return (self as String).isFloat()}
    func isAccount(_ min:Int,_ max:Int)->Bool{ return (self as String).isAccount(min,max)}
    func isIDCart()->Bool{ return (self as String).isIDCart()}
    
}
